import { request } from '@umijs/max';
import { message } from 'antd';
import { GSelect } from 'geminis-react';
import { forwardRef, useEffect, useRef, useState } from 'react';

export const ProductBatchSelect = forwardRef((props: any, ref: any) => {
  const [productFilter, setProductFilter] = useState<any>();
  const [productValue, setProductValue] = useState<any>();
  const [vendorValue, setVendorValue] = useState<any>();
  const batchRef = useRef<any>();
  const [loaded, setLoaded] = useState<boolean>(false);

  useEffect(() => {
    setProductFilter({ productId: productValue, vendorId: vendorValue });
  }, [productValue, vendorValue]);

  useEffect(() => {
    if (productFilter) {
      batchRef.current.loadData();
    }
  }, [productFilter]);

  useEffect(() => {
    if (props?.value && !loaded) {
      request('/api/warehouse/basic/productBatch/one?id=' + props.value)
        .then((resp: any) => {
          setProductValue(resp.product.id);
          setVendorValue(resp.vendor.id);
        }).catch(error => {
        message.error('获取物品信息错误');
        throw error;
      });
    }
    setLoaded(true);
  }, [props?.value]);

  return (
    <>
      <GSelect
        style={{ width: '30%' }}
        url="/api/warehouse/basic/vendor?deleted=false"
        showSearch
        onChange={setVendorValue}
        value={vendorValue}
      />
      <GSelect
        style={{ width: '30%' }}
        url="/api/warehouse/basic/product?deleted=false"
        showSearch
        onChange={setProductValue}
        value={productValue}
      />
      <GSelect
        style={{ width: '40%' }}
        ref={batchRef}
        url="/api/warehouse/basic/productBatch?deleted=false"
        autoload={'false'}
        showSearch
        fieldNames={{
          label: 'no',
          value: 'id',
        }}
        filter={productFilter}
        onChange={props?.onChange}
        value={props?.value}
      />
    </>
  );
});
